package com.dk.service.impl;

import com.dk.mapper.MenuRoleMapper;
import com.dk.mapper.RoleMapper;
import com.dk.mapper.RoleUserMapper;
import com.dk.pojo.MenuRoleExample;
import com.dk.pojo.Role;
import com.dk.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;
    @Autowired
    MenuRoleMapper menuRoleMapper;
    @Autowired
    RoleUserMapper roleUserMapper;

    @Override
    public List<Role> getInfo() {
        return roleMapper.selectByExample(null);
    }

    @Override
    public int insertInfo(Role role, Integer[] nodeids) {
        try {
            int i = roleMapper.insertRoleReturnId(role);
            Integer rid = role.getRid();
            int mrI = menuRoleMapper.insertMenuRole(rid, nodeids);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    @Override
    public Role getInfoByRid(Integer rid) {
        return roleMapper.selectByPrimaryKey(rid);
    }

    @Override
    public int updateRole(Role role, Integer[] nodeids) {
        try {
            //更新role并返回主键
            int i = roleMapper.updateRoleAndReturnPrimaryKey(role);
            Integer rid = role.getRid();
            //根据rid删除角色菜单中间表对应的mid
            MenuRoleExample example = new MenuRoleExample();
            MenuRoleExample.Criteria criteria = example.createCriteria();
            criteria.andRidEqualTo(rid);
            menuRoleMapper.deleteByExample(example);
            //重新添加mid
            int mrI = menuRoleMapper.insertMenuRole(rid, nodeids);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public int deleteRoleById(Integer rid) {
        try {
            //根据rid删除角色表数据
            roleMapper.deleteByPrimaryKey(rid);
            //删除中间表对应的数据
            MenuRoleExample example = new MenuRoleExample();
            MenuRoleExample.Criteria criteria = example.createCriteria();
            criteria.andRidEqualTo(rid);
            menuRoleMapper.deleteByExample(example);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    @Override
    public List<Integer> getInfoByUid(Integer uid) {
        return roleUserMapper.selectByUid(uid);
    }
}
